/**
 * 保存线程范围变量工具类
 */
package com.cnfangmao.threadscope;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

public class ThreadScopeVariableUtil {
	private static ThreadLocal<Map<String,Object>> mapVariables=new ThreadLocal<Map<String,Object>>();
	
	private final static String USER="#user#";  //用户对象关键字
	private final static String SESSION="#session#";  //session对象关键字
	
	/**
	 * 设置一个线程局部变量
	 * @param strKey
	 * @param objValue
	 */
	public static void setValue(String strKey,Object objValue)
	{
		Map<String,Object> mapLocal=mapVariables.get();
		if(mapLocal==null)
		{
			mapLocal=new HashMap<String,Object>();
			mapVariables.set(mapLocal);
		}
		
		mapLocal.put(strKey, objValue);
	}

	/**
	 * 把当前用户对象保存在线程范围
	 * @param strKey
	 * @param objValue
	 */
	public static void setUser(Object objUser)
	{
		Map<String,Object> mapLocal=mapVariables.get();
		if(mapLocal==null)
		{
			mapLocal=new HashMap<String,Object>();
			mapVariables.set(mapLocal);
		}
		
		mapLocal.put(USER, objUser);
	}

	/**
	 * 把当前Session对象保存在线程范围
	 * @param strKey
	 * @param objValue
	 */
	public static void setSession(HttpSession session)
	{
		Map<String,Object> mapLocal=mapVariables.get();
		if(mapLocal==null)
		{
			mapLocal=new HashMap<String,Object>();
			mapVariables.set(mapLocal);
		}
		
		mapLocal.put(SESSION, session);
	}
	/***
	 * 获取一个线程范围的变量
	 * @param strKey
	 * @return
	 */
	public static Object getValue(String strKey)
	{
		Object result=null;
		
		Map<String,Object> mapLocal=mapVariables.get();
		
		if(mapLocal!=null)
		{
			result=mapLocal.get(strKey);
		}
		
		return result;
	}
	

	/***
	 * 获取前当线程范围保存的用户变量
	 * @param strKey
	 * @return
	 */
	public static Object getUser()
	{
		Object result=null;
		
		Map<String,Object> mapLocal=mapVariables.get();
		
		if(mapLocal!=null)
		{
			result=mapLocal.get(USER);
		}
		
		return result;
	}
	
	/***
	 * 获取前当线程范围保存的Session
	 * @param strKey
	 * @return
	 */
	public static HttpSession getSession()
	{
		HttpSession result=null;
		
		Map<String,Object> mapLocal=mapVariables.get();
		
		if(mapLocal!=null)
		{
			Object object=mapLocal.get(SESSION);
			if(object instanceof HttpSession)
			{
				result=(HttpSession)object;
			}
		}
		
		return result;
	}
	
}
